<template>
  <div class="mb-4">
    <van-form @submit="onSubmit">
      <component
        :is="item.componentId"
        v-for="(item, index) in calcBaseInfo.slice(0, -3)"
        :key="item.code"
        :class="{ 'mt-2': index === 2 }"
        :prop-item="item"
        @accept="handleAccept"
      ></component>
      <component
        :is="item.componentId"
        v-for="item in supplement"
        :key="item.code"
        :prop-item="item"
        @accept="handleAccept"
      ></component>
      <component
        :is="item.componentId"
        v-for="(item, index) in calcBaseInfo.slice(-3)"
        :key="item.code"
        :class="{ 'mt-2': index === 0 }"
        :prop-item="item"
        @accept="handleAccept"
      ></component>
      <section v-if="code === 10703 || code === 10704" class="upload mt-2 py-3 px-4">
        <p class="line-height-xxl">
          文件上传： <br />
          需要上传的文件包括
          <span class="primary--text"> 门诊病历信息、</span>
          <span class="primary--text"> 各项检查报告</span>
          等信息。
        </p>
        <van-uploader v-model="fileList" :after-read="afterRead" @delete="deleteUploadedImg" />
      </section>
      <footer class="mt-12 px-10">
        <van-button type="primary" class="mb-3" round block native-type="submit"> 提交</van-button>
        <!-- <van-button type="primary" plain round block native-type="button" @click="backToHome"> 取消</van-button> -->
      </footer>
    </van-form>
  </div>
</template>
<script>
import { formatTime } from '@/utils';
import { fieldItemInput, fieldItemPicker, fieldItemRadio, fieldItemDate, fieldItemArea } from '@/components';
import { formatSubscribeType, formatSubscribeTypeSpecial } from '@/filters';
import { baseInfo } from './utils/config';

export default {
  name: '',
  head({ code }) {
    return {
      title: formatSubscribeType(code),
    };
  },
  validate({ query }) {
    return query.code;
  },
  async asyncData({ query, error, $siteConfig, $lvtongApis, $healthApis }) {
    const { data } = await $lvtongApis.getEquityCard(query.code)();
    // TODO created
    const cardId = data[0]?.id || '';
    const cardItemId = data[0]?.cardItemList[0]?.id || '';
    if (!cardId || !cardItemId) {
      return error({ message: '您暂时没有权益，预约失败！', showBackHome: true });
    }
    const channelInfo = await $healthApis
      .getHospitalAndCompanyFromSite({
        data: {
          site: $siteConfig.site,
          newCompanyId: $siteConfig.newCompanyId,
        },
      })
      .then((data) => data);
    return {
      channelInfo,
      cardId,
      cardItemId,
      code: query.code,
    };
  },
  components: {
    fieldItemInput,
    fieldItemPicker,
    fieldItemRadio,
    fieldItemDate,
    fieldItemArea,
  },
  data() {
    return {
      baseInfo,
      code: '',
      area: '', // 用于监听
      calcBaseInfo: [],
      fileList: [],
      fileUrl: [],
      // 渠道公司信息
      channelInfo: {},
    };
  },
  computed: {
    supplement() {
      return formatSubscribeTypeSpecial(this.code).extra;
    },
  },
  watch: {
    area: {
      async handler(newValue) {
        const hospital = await this.$$lvtongApis
          .getHospitalList(newValue)({ loading: true })
          .then(({ data }) => data || []);
        hospital.forEach((item) => {
          item.label = item.name;
          item.code = item.hospitalId;
        });
        this.hospitalId = '';
        this.baseInfo[1].columns = hospital;
        this.baseInfo[1].disabled = !hospital.length;
        this.baseInfo[1].disabledText = hospital.length ? '' : '所选地区无医院';
      },
      deep: true,
    },
    baseInfo: {
      handler(newValue) {
        this.calcBaseInfo = newValue;
      },
      deep: true,
    },
  },
  created() {
    if (!this.cardId || !this.cardItemId) {
      this.$toast({ message: '您暂时没有权益，预约失败' });
      const backHomeUrl = getBackHomeUrl();
      backHomeUrl ? absoluteGo(backHomeUrl) : this.goTo({ name: 'home' });
    }
  },
  mounted() {
    this.calcBaseInfo = this.baseInfo;
  },
  methods: {
    handleAccept(item) {
      this[item.code] = item.value;
    },
    async onSubmit() {
      const success = this.validator();
      if (success) {
        const {
          costType,
          departmentName,
          diagnosisType,
          doctorName,
          hospitalId,
          isAdmissionNotice,
          operationType,
          outpatientType,
          roomType,
          subscribeDateEarliest,
          subscribeDateLatest,
          remark,
          isAccompany,
        } = this;
        const {
          hospitalId: channelId,
          hospitalName: channelName,
          newCompanyId: companyId,
          newCompanyName: companyName,
        } = this.channelInfo;
        const data = {
          channelId, // 代表绿通
          channelName,
          companyId,
          companyName,
          cardItemId: this.cardItemId, // 卡单项权益id
          cardId: this.cardId, // 卡Id
          costType,
          departmentName,
          diagnosisType,
          hospitalId,
          remark,
          subscribeDateEarliest: formatTime(subscribeDateEarliest, 'YYYY-MM-DD hh:mm:ss'),
          subscribeDateLatest: formatTime(subscribeDateLatest, 'YYYY-MM-DD hh:mm:ss'),
          subscribeType: this.code,
          isAccompany: isAccompany === 11302,
        };

        switch (String(this.code)) {
          case '10702':
            data.outpatientType = outpatientType;
            data.doctorName = doctorName;
            break;
          case '10703':
            data.doctorName = doctorName;
            data.operationType = operationType;
            data.outpatientType = outpatientType;
            data.roomType = roomType;
            data.fileUrl = this.fileUrl;
            break;
          case '10704':
            data.doctorName = doctorName;
            data.isAdmissionNotice = isAdmissionNotice;
            data.fileUrl = this.fileUrl;
            break;
          default:
            break;
        }
        await this.$$lvtongApis.submitSubscribe({ data, loading: true }).then(({ data }) => {
          this.goTo({ name: 'results', query: { subscribeId: data?.subscribeId } }, true);
        });
      }
    },
    validator() {
      const blankValueValidator = baseInfo.some((item) => {
        if (this[item.code] || item.unnecessary) {
          return false;
        } else {
          this.$toast(item.placeholder);
          return true;
        }
      });
      const supplementBlankValueValidator = this.supplement.some((item) => {
        if (this[item.code] || this[item.code] === 0 || item.unnecessary) {
          return false;
        } else {
          this.$toast(item.placeholder);
          return true;
        }
      });
      if (blankValueValidator || supplementBlankValueValidator) {
        return false;
      }
      if (this.subscribeDateEarliest > this.subscribeDateLatest) {
        this.$toast('最晚时间早于最早时间');
        return false;
      }
      return true;
    },
    afterRead(file, index) {
      const form = new FormData();
      form.append('file', file.file);
      this.$$lvtongApis.uploadImg({ data: form, loading: true }).then(({ data }) => {
        if (data) {
          this.fileUrl.push(data);
        } else {
          this.fileList.splice(index.index, 1);
          this.$toast('图片上传失败');
        }
      });
    },
    deleteUploadedImg(file, index) {
      this.fileUrl.splice(index.index, 1);
    },
  },
};
</script>
<style scoped lang="less">
.upload {
  background: #fff;
}
/deep/ .van-uploader__preview {
  margin: 0 5px 8px 0;
}
</style>
